<template>
  <div class="bankcard-management">
    <el-card class="main-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>银行卡管理</span>
          <el-tag type="warning" v-if="!bankCardStatus.isBound">未绑定</el-tag>
          <el-tag type="success" v-else>已绑定</el-tag>
        </div>
      </template>

      <!-- 安全提示 -->
      <el-alert
        title="安全提示"
        type="info"
        :closable="false"
        show-icon
        class="security-alert"
      >
        <template #default>
          <p>为了保障您的资金安全，充值和保证金缴纳需要绑定本人银行卡。</p>
          <p>请确保银行卡持卡人姓名与身份证姓名一致。</p>
        </template>
      </el-alert>

      <!-- 身份证认证步骤 -->
      <div v-if="!bankCardStatus.idCardVerified" class="step-section">
        <h3>第一步：身份证实名认证</h3>
        <el-form
          ref="idCardFormRef"
          :model="idCardForm"
          :rules="idCardRules"
          label-width="120px"
          class="id-card-form"
        >
          <el-form-item label="真实姓名" prop="realName">
            <el-input
              v-model="idCardForm.realName"
              placeholder="请输入身份证上的真实姓名"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCardNumber">
            <el-input
              v-model="idCardForm.idCardNumber"
              placeholder="请输入18位身份证号码"
              maxlength="18"
            />
          </el-form-item>
          <el-form-item label="身份证正面" prop="idCardFront">
            <el-upload
              class="id-card-upload"
              :show-file-list="false"
              :before-upload="beforeUploadIdCard"
              action="#"
              :http-request="uploadIdCardFront"
            >
              <img v-if="idCardForm.idCardFront" :src="idCardForm.idCardFront" class="id-card-image" />
              <el-icon v-else class="id-card-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">请上传身份证正面照片</div>
          </el-form-item>
          <el-form-item label="身份证反面" prop="idCardBack">
            <el-upload
              class="id-card-upload"
              :show-file-list="false"
              :before-upload="beforeUploadIdCard"
              action="#"
              :http-request="uploadIdCardBack"
            >
              <img v-if="idCardForm.idCardBack" :src="idCardForm.idCardBack" class="id-card-image" />
              <el-icon v-else class="id-card-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">请上传身份证反面照片</div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="idCardVerifying"
              @click="submitIdCardVerification"
            >
              提交认证
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 银行卡绑定步骤 -->
      <div v-if="bankCardStatus.idCardVerified && !bankCardStatus.isBound" class="step-section">
        <h3>第二步：绑定银行卡</h3>
        <el-form
          ref="bankCardFormRef"
          :model="bankCardForm"
          :rules="bankCardRules"
          label-width="120px"
          class="bank-card-form"
        >
          <el-form-item label="银行卡号" prop="cardNumber">
            <el-input
              v-model="bankCardForm.cardNumber"
              placeholder="请输入银行卡号"
              maxlength="19"
              @input="formatCardNumber"
            />
          </el-form-item>
          <el-form-item label="开户银行" prop="bankName">
            <el-select v-model="bankCardForm.bankName" placeholder="请选择开户银行" style="width: 100%">
              <el-option label="中国工商银行" value="工商银行" />
              <el-option label="中国建设银行" value="建设银行" />
              <el-option label="中国农业银行" value="农业银行" />
              <el-option label="中国银行" value="中国银行" />
              <el-option label="招商银行" value="招商银行" />
              <el-option label="中信银行" value="中信银行" />
              <el-option label="光大银行" value="光大银行" />
              <el-option label="华夏银行" value="华夏银行" />
              <el-option label="民生银行" value="民生银行" />
              <el-option label="广发银行" value="广发银行" />
              <el-option label="平安银行" value="平安银行" />
              <el-option label="浦发银行" value="浦发银行" />
            </el-select>
          </el-form-item>
          <el-form-item label="卡片类型" prop="cardType">
            <el-radio-group v-model="bankCardForm.cardType">
              <el-radio label="debit">储蓄卡</el-radio>
              <el-radio label="credit">信用卡</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="持卡人姓名" prop="holderName">
            <el-input
              v-model="bankCardForm.holderName"
              placeholder="请输入持卡人姓名"
              maxlength="20"
              :disabled="true"
            />
            <div class="form-tip">持卡人姓名必须与身份证姓名一致</div>
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input
              v-model="bankCardForm.phoneNumber"
              placeholder="请输入银行预留手机号"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="短信验证码" prop="smsCode">
            <div class="sms-input-group">
              <el-input
                v-model="bankCardForm.smsCode"
                placeholder="请输入短信验证码"
                maxlength="6"
              />
              <el-button
                :disabled="smsCountdown > 0 || !bankCardForm.phoneNumber"
                @click="sendSmsVerification"
              >
                {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="bankCardBinding"
              @click="submitBankCardBinding"
            >
              绑定银行卡
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 已绑定银行卡信息 -->
      <div v-if="bankCardStatus.isBound" class="bound-card-section">
        <h3>已绑定银行卡</h3>
        <div class="bank-card-info">
          <div class="card-item">
            <span class="label">开户银行：</span>
            <span class="value">{{ bankCardStatus.bankCard.bankName }}</span>
          </div>
          <div class="card-item">
            <span class="label">银行卡号：</span>
            <span class="value">{{ bankCardStatus.bankCard.cardNumber }}</span>
          </div>
          <div class="card-item">
            <span class="label">卡片类型：</span>
            <span class="value">{{ bankCardStatus.bankCard.cardType === 'debit' ? '储蓄卡' : '信用卡' }}</span>
          </div>
          <div class="card-item">
            <span class="label">绑定时间：</span>
            <span class="value">{{ formatTime(bankCardStatus.bankCard.bindTime) }}</span>
          </div>
        </div>
        <div class="card-actions">
          <el-button type="danger" @click="showUnbindDialog">解绑银行卡</el-button>
        </div>
      </div>
    </el-card>

    <!-- 解绑确认对话框 -->
    <el-dialog
      v-model="unbindDialogVisible"
      title="解绑银行卡"
      width="400px"
    >
      <el-alert
        title="解绑风险提示"
        type="warning"
        :closable="false"
        show-icon
      >
        解绑银行卡后将无法进行充值和保证金缴纳操作，请谨慎操作。
      </el-alert>
      <el-form
        ref="unbindFormRef"
        :model="unbindForm"
        :rules="unbindRules"
        label-width="120px"
        style="margin-top: 20px;"
      >
        <el-form-item label="支付密码" prop="password">
          <el-input
            v-model="unbindForm.password"
            type="password"
            placeholder="请输入支付密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="短信验证码" prop="smsCode">
          <div class="sms-input-group">
            <el-input
              v-model="unbindForm.smsCode"
              placeholder="请输入短信验证码"
              maxlength="6"
            />
            <el-button
              :disabled="unbindSmsCountdown > 0"
              @click="sendUnbindSms"
            >
              {{ unbindSmsCountdown > 0 ? `${unbindSmsCountdown}s后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="unbindDialogVisible = false">取消</el-button>
        <el-button
          type="danger"
          :loading="unbindProcessing"
          @click="confirmUnbind"
        >
          确认解绑
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getBankCardStatus,
  verifyIdCard,
  bindBankCard,
  unbindBankCard,
  sendSmsCode
} from '@/api/bankcard'

// 银行卡状态
const bankCardStatus = ref({
  isBound: false,
  bankCard: null,
  idCardVerified: false
})

// 身份证认证表单
const idCardFormRef = ref()
const idCardForm = reactive({
  realName: '',
  idCardNumber: '',
  idCardFront: '',
  idCardBack: ''
})

const idCardRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
  ],
  idCardNumber: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  idCardFront: [
    { required: true, message: '请上传身份证正面照片', trigger: 'change' }
  ],
  idCardBack: [
    { required: true, message: '请上传身份证反面照片', trigger: 'change' }
  ]
}

const idCardVerifying = ref(false)

// 银行卡绑定表单
const bankCardFormRef = ref()
const bankCardForm = reactive({
  cardNumber: '',
  bankName: '',
  cardType: 'debit',
  holderName: '',
  phoneNumber: '',
  smsCode: ''
})

const bankCardRules = {
  cardNumber: [
    { required: true, message: '请输入银行卡号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行卡号', trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: '请选择开户银行', trigger: 'change' }
  ],
  cardType: [
    { required: true, message: '请选择卡片类型', trigger: 'change' }
  ],
  holderName: [
    { required: true, message: '请输入持卡人姓名', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
}

const bankCardBinding = ref(false)
const smsCountdown = ref(0)
const smsTimer = ref(null)

// 解绑相关
const unbindDialogVisible = ref(false)
const unbindFormRef = ref()
const unbindForm = reactive({
  password: '',
  smsCode: ''
})

const unbindRules = {
  password: [
    { required: true, message: '请输入支付密码', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
}

const unbindProcessing = ref(false)
const unbindSmsCountdown = ref(0)
const unbindSmsTimer = ref(null)

// 获取银行卡状态
const getBankCardStatusData = async () => {
  try {
    const response = await getBankCardStatus()
    if (response.code === 200) {
      bankCardStatus.value = response.data
      
      // 如果身份证已验证，自动填充持卡人姓名
      if (response.data.idCardVerified && response.data.realName) {
        bankCardForm.holderName = response.data.realName
      }
    }
  } catch (error) {
    console.error('获取银行卡状态失败:', error)
    ElMessage.error('获取银行卡状态失败')
  }
}

// 身份证照片上传前验证
const beforeUploadIdCard = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('身份证照片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('身份证照片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传身份证正面
const uploadIdCardFront = (options) => {
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    idCardForm.idCardFront = e.target.result
  }
  reader.readAsDataURL(file)
}

// 上传身份证反面
const uploadIdCardBack = (options) => {
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    idCardForm.idCardBack = e.target.result
  }
  reader.readAsDataURL(file)
}

// 提交身份证认证
const submitIdCardVerification = async () => {
  if (!idCardFormRef.value) return

  try {
    await idCardFormRef.value.validate()
    idCardVerifying.value = true

    const response = await verifyIdCard(idCardForm)
    if (response.code === 200) {
      ElMessage.success('身份证认证成功')
      await getBankCardStatusData()
      
      // 自动填充持卡人姓名
      bankCardForm.holderName = idCardForm.realName
    } else {
      throw new Error(response.message || '身份证认证失败')
    }
  } catch (error) {
    console.error('身份证认证失败:', error)
    ElMessage.error(error.message || '身份证认证失败')
  } finally {
    idCardVerifying.value = false
  }
}

// 格式化银行卡号
const formatCardNumber = () => {
  // 移除所有非数字字符
  bankCardForm.cardNumber = bankCardForm.cardNumber.replace(/\D/g, '')
}

// 发送短信验证码
const sendSmsVerification = async () => {
  try {
    const response = await sendSmsCode({
      phoneNumber: bankCardForm.phoneNumber,
      type: 'bind'
    })
    
    if (response.code === 200) {
      ElMessage.success('短信验证码发送成功')
      startSmsCountdown()
    } else {
      throw new Error(response.message || '发送短信验证码失败')
    }
  } catch (error) {
    console.error('发送短信验证码失败:', error)
    ElMessage.error(error.message || '发送短信验证码失败')
  }
}

// 开始短信倒计时
const startSmsCountdown = () => {
  smsCountdown.value = 60
  smsTimer.value = setInterval(() => {
    smsCountdown.value--
    if (smsCountdown.value <= 0) {
      clearInterval(smsTimer.value)
    }
  }, 1000)
}

// 提交银行卡绑定
const submitBankCardBinding = async () => {
  if (!bankCardFormRef.value) return

  try {
    await bankCardFormRef.value.validate()
    bankCardBinding.value = true

    const response = await bindBankCard(bankCardForm)
    if (response.code === 200) {
      ElMessage.success('银行卡绑定成功')
      await getBankCardStatusData()
    } else {
      throw new Error(response.message || '银行卡绑定失败')
    }
  } catch (error) {
    console.error('银行卡绑定失败:', error)
    ElMessage.error(error.message || '银行卡绑定失败')
  } finally {
    bankCardBinding.value = false
  }
}

// 显示解绑对话框
const showUnbindDialog = () => {
  unbindDialogVisible.value = true
}

// 发送解绑短信验证码
const sendUnbindSms = async () => {
  try {
    const response = await sendSmsCode({
      phoneNumber: bankCardStatus.value.bankCard.phoneNumber,
      type: 'unbind'
    })
    
    if (response.code === 200) {
      ElMessage.success('短信验证码发送成功')
      startUnbindSmsCountdown()
    } else {
      throw new Error(response.message || '发送短信验证码失败')
    }
  } catch (error) {
    console.error('发送短信验证码失败:', error)
    ElMessage.error(error.message || '发送短信验证码失败')
  }
}

// 开始解绑短信倒计时
const startUnbindSmsCountdown = () => {
  unbindSmsCountdown.value = 60
  unbindSmsTimer.value = setInterval(() => {
    unbindSmsCountdown.value--
    if (unbindSmsCountdown.value <= 0) {
      clearInterval(unbindSmsTimer.value)
    }
  }, 1000)
}

// 确认解绑
const confirmUnbind = async () => {
  if (!unbindFormRef.value) return

  try {
    await unbindFormRef.value.validate()
    
    await ElMessageBox.confirm(
      '解绑银行卡后将无法进行充值和保证金缴纳，确定要解绑吗？',
      '确认解绑',
      {
        confirmButtonText: '确定解绑',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    unbindProcessing.value = true

    const response = await unbindBankCard(unbindForm)
    if (response.code === 200) {
      ElMessage.success('银行卡解绑成功')
      unbindDialogVisible.value = false
      await getBankCardStatusData()
    } else {
      throw new Error(response.message || '银行卡解绑失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('银行卡解绑失败:', error)
      ElMessage.error(error.message || '银行卡解绑失败')
    }
  } finally {
    unbindProcessing.value = false
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  return new Date(timeString).toLocaleString('zh-CN')
}

// 页面初始化
onMounted(async () => {
  await getBankCardStatusData()
})
</script>

<style scoped>
.bankcard-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.main-card {
  border-radius: 12px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-alert {
  margin-bottom: 30px;
}

.step-section {
  margin-bottom: 40px;
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
}

.step-section h3 {
  margin: 0 0 20px 0;
  color: #1f2937;
  font-size: 18px;
}

.id-card-form,
.bank-card-form {
  max-width: 600px;
}

.id-card-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.id-card-upload:hover {
  border-color: #409eff;
}

.id-card-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.id-card-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
}

.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #6b7280;
}

.sms-input-group {
  display: flex;
  gap: 12px;
}

.sms-input-group .el-input {
  flex: 1;
}

.bound-card-section {
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
}

.bound-card-section h3 {
  margin: 0 0 20px 0;
  color: #1f2937;
  font-size: 18px;
}

.bank-card-info {
  margin-bottom: 20px;
}

.card-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
}

.card-item .label {
  width: 100px;
  color: #6b7280;
}

.card-item .value {
  color: #1f2937;
  font-weight: 500;
}

.card-actions {
  text-align: right;
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

:deep(.el-alert__content) {
  line-height: 1.6;
}
</style>
